<template>
  <div class="pregnancy-examination-container">
    <div class="search-form">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="妊检日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item label="种母耳号">
          <el-select 
            v-model="queryParams.earTag" 
            placeholder="请选择种母耳号" 
            clearable 
            filterable
            style="width: 180px;"
          >
            <el-option 
              v-for="(name, id) in earNumberMap" 
              :key="id" 
              :label="name" 
              :value="id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人">
          <el-select v-model="queryParams.responsiblePerson" placeholder="请选择负责人" clearable style="width: 160px;">
            <el-option v-for="item in responsiblePersonOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="妊检结果">
          <el-select v-model="queryParams.pregnancyResult" placeholder="请选择妊检结果" clearable style="width: 160px;">
            <el-option v-for="item in pregnancyResultOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="胎数">
          <el-input v-model="queryParams.fetusCount" placeholder="请输入胎数" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 调试区域 -->
    <div class="debug-panel" v-if="showDebug">
      <h3>调试面板</h3>
      <div class="debug-actions">
        <el-button type="warning" @click="testDirectFetch">直接获取数据</el-button>
        <el-button type="warning" @click="testMockData">使用模拟数据</el-button>
        <el-button type="danger" @click="closeDebug">关闭调试</el-button>
      </div>
      <div class="debug-info" v-if="debugInfo">
        <pre>{{ debugInfo }}</pre>
      </div>
    </div>

    <div class="table-container">
      <div class="operation-btns">
        <el-button type="primary" @click="goToAddPage">新增</el-button>
        <el-button type="info" @click="showDebug = true">调试</el-button>
      </div>
      
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="ExaminationId" label="ID" width="80" />
        <el-table-column prop="EarTag" label="种母耳号" width="120">
          <template #default="scope">
            {{ formatEarTag(scope.row.EarTag) }}
          </template>
        </el-table-column>
        <el-table-column prop="PregnancyCheckDate" label="妊检日期" width="150" :formatter="formatDate" />
        <el-table-column prop="PregnancyResult" label="妊检结果" width="120" />
        <el-table-column prop="PregnancyMethod" label="妊检方法" width="120" />
        <el-table-column prop="FetusCount" label="胎数" width="80" />
        <el-table-column prop="GestationDays" label="妊娠天数" width="100" />
        <el-table-column prop="CurrentPen" label="当前栏位" width="120">
          <template #default="scope">
            {{ formatBuilding(scope.row.CurrentPen) }}
          </template>
        </el-table-column>
        <el-table-column prop="CurrentStall" label="当前栏号" width="120">
          <template #default="scope">
            {{ formatPen(scope.row.CurrentStall) }}
          </template>
        </el-table-column>
        <el-table-column prop="TransferPen" label="转入栏位" width="120">
          <template #default="scope">
            {{ formatBuilding(scope.row.TransferPen) }}
          </template>
        </el-table-column>
        <el-table-column prop="TransferStall" label="转入栏号" width="120">
          <template #default="scope">
            {{ formatPen(scope.row.TransferStall) }}
          </template>
        </el-table-column>
        <el-table-column prop="ResponsiblePerson" label="负责人" width="120" />
        <el-table-column prop="Creator" label="创建人" width="120" />
        <el-table-column prop="CreateTime" label="创建时间" width="150" :formatter="formatDate" />
        <el-table-column prop="Modifier" label="修改人" width="120" />
        <el-table-column prop="ModifyTime" label="修改时间" width="150" :formatter="formatDate" />
        <el-table-column prop="Approver" label="审核人" width="120" />
        <el-table-column prop="ApprovalTime" label="审核时间" width="150" :formatter="formatDate" />
        <el-table-column prop="DocumentNumber" label="单据号" width="120" />
        <el-table-column prop="RecordType" label="记录类型" width="120" />
        <el-table-column prop="Status" label="状态" width="120">
          <template #default="scope">
            <el-tag 
              :type="scope.row.Status === '已删除' ? 'danger' : (scope.row.Status === '待审核' ? 'warning' : 'success')" 
              effect="plain"
            >
              {{ scope.row.Status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)" :disabled="scope.row.Status === '已删除'">编辑</el-button>
            <el-button 
              v-if="scope.row.Status !== '已删除'" 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
            <el-button 
              v-else
              size="small" 
              type="info" 
              disabled
            >
              已删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <span>共 {{ total }} 条</span>
        <el-select v-model="queryParams.pageSize" style="width: 100px; margin-left: 10px;">
          <el-option :value="10" label="10条/页" />
          <el-option :value="20" label="20条/页" />
          <el-option :value="50" label="50条/页" />
          <el-option :value="100" label="100条/页" />
        </el-select>
        <el-pagination
          :current-page="queryParams.pageIndex"
          :page-size="queryParams.pageSize"
          layout="prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          hide-on-single-page
        />
        <span>前往</span>
        <el-input v-model="goToPage" style="width: 50px; margin: 0 5px;" @keyup.enter="handleGoToPage" />
        <span>页</span>
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增种母妊检记录' : '编辑种母妊检记录'"
      width="800px"
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="种母耳号" prop="EarTag">
              <el-input v-model="form.EarTag" placeholder="请输入种母耳号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="妊检日期" prop="PregnancyCheckDate">
              <el-date-picker
                v-model="form.PregnancyCheckDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="妊检结果" prop="PregnancyResult">
              <el-select v-model="form.PregnancyResult" placeholder="请选择妊检结果" style="width: 100%">
                <el-option v-for="item in pregnancyResultOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="妊检方法" prop="PregnancyMethod">
              <el-input v-model="form.PregnancyMethod" placeholder="请输入妊检方法" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="胎数" prop="FetusCount">
              <el-input-number v-model="form.FetusCount" :min="0" :controls="true" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="妊娠天数" prop="GestationDays">
              <el-input-number v-model="form.GestationDays" :min="0" :controls="true" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="当前栏位" prop="CurrentPen">
              <el-select v-model="form.CurrentPen" placeholder="请选择当前栏位" style="width: 100%">
                <el-option v-for="(name, id) in buildingMap" :key="id" :label="name" :value="id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前栏号" prop="CurrentStall">
              <el-select v-model="form.CurrentStall" placeholder="请选择当前栏号" style="width: 100%">
                <el-option v-for="(name, id) in penMap" :key="id" :label="name" :value="id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="转入栏位" prop="TransferPen">
              <el-select v-model="form.TransferPen" placeholder="请选择转入栏位" style="width: 100%">
                <el-option v-for="(name, id) in buildingMap" :key="id" :label="name" :value="id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="转入栏号" prop="TransferStall">
              <el-select v-model="form.TransferStall" placeholder="请选择转入栏号" style="width: 100%">
                <el-option v-for="(name, id) in penMap" :key="id" :label="name" :value="id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="负责人" prop="ResponsiblePerson">
              <el-select v-model="form.ResponsiblePerson" placeholder="请选择负责人" style="width: 100%">
                <el-option v-for="item in responsiblePersonOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建人" prop="Creator">
              <el-input v-model="form.Creator" placeholder="请输入创建人" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="创建时间" prop="CreateTime">
              <el-date-picker
                v-model="form.CreateTime"
                type="datetime"
                placeholder="选择创建时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="修改人" prop="Modifier">
              <el-input v-model="form.Modifier" placeholder="请输入修改人" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="修改时间" prop="ModifyTime">
              <el-date-picker
                v-model="form.ModifyTime"
                type="datetime"
                placeholder="选择修改时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核人" prop="Approver">
              <el-input v-model="form.Approver" placeholder="请输入审核人" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="审核时间" prop="ApprovalTime">
              <el-date-picker
                v-model="form.ApprovalTime"
                type="datetime"
                placeholder="选择审核时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单据号" prop="DocumentNumber">
              <el-input v-model="form.DocumentNumber" placeholder="请输入单据号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="记录类型" prop="RecordType">
              <el-input v-model="form.RecordType" placeholder="请输入记录类型" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="Status">
              <el-input v-model="form.Status" placeholder="请输入状态" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { 
  getPregnancyExaminationList, 
  addPregnancyExamination, 
  updatePregnancyExamination, 
  deletePregnancyExamination,
  batchDeletePregnancyExamination
} from '../../utils/requestPregnancyExamination'
import axios from 'axios'
import { Sheep_BreedingRead, serviceRead } from '../../utils/Interceptors' // 修正导入

// 添加路由
const router = useRouter()

// 调试状态
const showDebug = ref(false)
const debugInfo = ref('')

// 查询参数
const queryParams = reactive({
  pageIndex: 1,
  pageSize: 20,
  startDate: '',
  endDate: '',
  earTag: '',
  responsiblePerson: '',
  pregnancyResult: '',
  fetusCount: '',
  excludeDeleted: true // 默认排除已删除的数据
})

// 是否显示已删除数据
const showDeleted = ref(false)

// 跳转页码
const goToPage = ref('')

// 日期范围
const dateRange = ref<string[]>([])

// 负责人选项
const responsiblePersonOptions = ref<Array<{label: string, value: string}>>([])

// 获取用户列表
const fetchUserList = async () => {
  try {
    const res = await serviceRead.get('/api/User/SraechUser', {
      params: { PageIndex: 1, PageSize: 100 }
    })
    if (res.data && res.data.code === 200 && Array.isArray(res.data.PageData)) {
      responsiblePersonOptions.value = res.data.PageData.map((user: any) => ({
        label: user.UserName,
        value: user.UserName
      }))
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 妊检结果选项
const pregnancyResultOptions = ref([
  { label: '阳性', value: '阳性' },
  { label: '阴性', value: '阴性' },
  { label: '待定', value: '待定' }
])

// 表格数据
const tableData = ref<any[]>([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref<any[]>([])
const earNumberMap = ref<Record<string, string>>({}) // 用于存储耳号ID到耳号名称的映射
const buildingMap = ref<Record<string, string>>({}) // 用于存储栏位ID到名称的映射
const penMap = ref<Record<string, string>>({}) // 用于存储栏号ID到名称的映射

// 获取耳号列表，用于将ID转换为显示名称
const fetchEarNumberList = async () => {
  try {
    const res = await Sheep_BreedingRead.get('/api/EliminationInfo/GetSheepFilesIdEarNumber')
    if (res.data && res.data.code === 200 && res.data.data) {
      // 构建耳号ID到名称的映射
      const map: Record<string, string> = {}
      res.data.data.forEach((item: any) => {
        if (item && item.Id && item.Name) {
          map[item.Id] = item.Name
        }
      })
      earNumberMap.value = map
      console.log('耳号映射表:', earNumberMap.value)
    }
  } catch (error) {
    console.error('获取耳号列表失败:', error)
  }
}

// 获取栋舍栏位列表
const fetchBuildingList = async () => {
  try {
    const res = await Sheep_BreedingRead.get('/api/Sheepfarm/SearchBuildingManagement', {
      params: { PageIndex: 1, PageSize: 100 }
    })
    if (res.data && res.data.code === 200 && res.data.PageData) {
      // 构建栏位ID到名称的映射
      const map: Record<string, string> = {}
      res.data.PageData.forEach((item: any) => {
        if (item && item.BuildingId && item.House_name) {
          map[item.BuildingId] = item.House_name
        }
      })
      buildingMap.value = map
      console.log('栏位映射表:', buildingMap.value)
    }
  } catch (error) {
    console.error('获取栏位列表失败:', error)
  }
}

// 获取栏号列表
const fetchPenList = async () => {
  try {
    const res = await Sheep_BreedingRead.get('/api/EliminationInfo/GetFieldManagementIdName')
    if (res.data && res.data.code === 200 && res.data.data) {
      // 构建栏号ID到名称的映射
      const map: Record<string, string> = {}
      res.data.data.forEach((item: any) => {
        if (item && item.Id && item.Name) {
          map[item.Id] = item.Name
        }
      })
      penMap.value = map
      console.log('栏号映射表:', penMap.value)
    }
  } catch (error) {
    console.error('获取栏号列表失败:', error)
  }
}

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref()
const form = reactive({
  ExaminationId: '',
  EarTag: '',
  PregnancyCheckDate: '',
  PregnancyResult: '',
  PregnancyMethod: '',
  FetusCount: 0,
  GestationDays: 0,
  CurrentPen: '',
  CurrentStall: '',
  TransferPen: '',
  TransferStall: '',
  ResponsiblePerson: '',
  Creator: '',
  CreateTime: '',
  Modifier: '',
  ModifyTime: '',
  Approver: '',
  ApprovalTime: '',
  DocumentNumber: '',
  RecordType: '',
  Status: ''
})

// 表单校验规则
const rules = {
  EarTag: [{ required: true, message: '请输入种母耳号', trigger: 'blur' }],
  PregnancyCheckDate: [{ required: true, message: '请选择妊检日期', trigger: 'change' }],
  ResponsiblePerson: [{ required: true, message: '请选择负责人', trigger: 'change' }],
  PregnancyResult: [{ required: true, message: '请选择妊检结果', trigger: 'change' }]
}

// 生命周期
onMounted(async () => {
  // 先加载所有映射数据
  await Promise.all([
    fetchEarNumberList(), 
    fetchBuildingList(), 
    fetchPenList(),
    fetchUserList()
  ])
  
  // 然后加载表格数据
  fetchTableData()
})

// 方法
// 处理日期变化
const handleDateChange = (val: string[]) => {
  if (val) {
    queryParams.startDate = val[0]
    queryParams.endDate = val[1]
  } else {
    queryParams.startDate = ''
    queryParams.endDate = ''
  }
}

// 查询
const handleQuery = async () => {
  queryParams.pageIndex = 1
  
  // 确保先加载耳号映射表
  if (Object.keys(earNumberMap.value).length === 0) {
    await fetchEarNumberList()
  }
  if (Object.keys(buildingMap.value).length === 0) {
    await fetchBuildingList()
  }
  if (Object.keys(penMap.value).length === 0) {
    await fetchPenList()
  }
  
  fetchTableData()
}

// 重置查询
const resetQuery = () => {
  dateRange.value = []
  showDeleted.value = false
  Object.assign(queryParams, {
    pageIndex: 1,
    pageSize: 20,
    startDate: '',
    endDate: '',
    earTag: '',
    responsiblePerson: '',
    pregnancyResult: '',
    fetusCount: '',
    excludeDeleted: true
  })
  fetchTableData()
}

// 添加调试方法
const logData = (item: any) => {
  console.log('数据项字段：', Object.keys(item))
  console.log('数据项内容：', item)
}

// 获取表格数据
const fetchTableData = async () => {
  loading.value = true
  try {
    debugInfo.value = '正在请求数据...'
    // 确保排除已删除数据的参数生效
    const params = {
      ...queryParams,
      excludeDeleted: true // 强制排除已删除数据
    }
    
    const res = await getPregnancyExaminationList(params)
    debugInfo.value += '\n请求成功，状态码: ' + res.status
    
    // 从控制台可以看到数据结构
    if (res.status === 200 && res.data) {
      // 打印出数据结构以便调试
      console.log('返回数据结构:', res.data)
      debugInfo.value += '\n数据结构: ' + JSON.stringify(res.data, null, 2)
      
      // 确保先加载耳号映射表
      if (Object.keys(earNumberMap.value).length === 0) {
        await fetchEarNumberList()
      }
      if (Object.keys(buildingMap.value).length === 0) {
        await fetchBuildingList()
      }
      if (Object.keys(penMap.value).length === 0) {
        await fetchPenList()
      }
      
      // 根据实际的数据结构解析 - 注意大写的PageData和嵌套的data属性
      if (res.data.data && res.data.data.PageData && Array.isArray(res.data.data.PageData)) {
        // 过滤掉已删除的数据
        tableData.value = res.data.data.PageData.filter((item: any) => item.Status !== '已删除')
        total.value = tableData.value.length
        console.log('表格数据(过滤后):', tableData.value)
        debugInfo.value += '\n成功获取到 ' + tableData.value.length + ' 条数据(已过滤已删除)'
      } else if (res.data.PageData && Array.isArray(res.data.PageData)) {
        // 备选路径
        tableData.value = res.data.PageData.filter((item: any) => item.Status !== '已删除')
        total.value = tableData.value.length
        console.log('表格数据(备选路径,过滤后):', tableData.value)
        debugInfo.value += '\n通过备选路径获取到 ' + tableData.value.length + ' 条数据(已过滤已删除)'
      } else {
        tableData.value = []
        total.value = 0
        console.log('没有找到PageData数组')
        debugInfo.value += '\n没有找到PageData数组，尝试查找任何数组数据...'
        
        // 深度搜索任何可能的数组
        const findArrays = (obj: any, path = '') => {
          if (!obj || typeof obj !== 'object') return;
          
          Object.entries(obj).forEach(([key, value]) => {
            const currentPath = path ? `${path}.${key}` : key;
            if (Array.isArray(value) && value.length > 0) {
              console.log(`找到数组: ${currentPath}, 长度: ${value.length}`, value);
              debugInfo.value += `\n找到数组: ${currentPath}, 长度: ${value.length}`;
              
              // 尝试使用第一个找到的非空数组，并过滤已删除
              if (tableData.value.length === 0) {
                tableData.value = value.filter((item: any) => item.Status !== '已删除')
                total.value = tableData.value.length
                debugInfo.value += `\n使用路径 ${currentPath} 的数据(已过滤已删除)`
              }
            }
            
            // 递归搜索更深层次
            findArrays(value, currentPath);
          });
        };
        
        findArrays(res.data);
      }
    } else {
      console.error('API返回状态码不是200:', res.status)
      debugInfo.value += '\nAPI返回状态码不是200: ' + res.status
      ElMessage.error('获取数据失败')
    }
  } catch (error) {
    console.error('获取种母妊检数据失败:', error)
    debugInfo.value += '\n获取数据失败: ' + JSON.stringify(error)
    ElMessage.error('获取数据失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 直接获取数据测试（不使用参数）
const testDirectFetch = async () => {
  loading.value = true
  debugInfo.value = '正在直接获取数据（无参数）...'
  
  // 确保先加载耳号映射表
  if (Object.keys(earNumberMap.value).length === 0) {
    await fetchEarNumberList()
  }
  if (Object.keys(buildingMap.value).length === 0) {
    await fetchBuildingList()
  }
  if (Object.keys(penMap.value).length === 0) {
    await fetchPenList()
  }
  
  // 递归查找任何数组数据
  const findArrays = (obj: any, path = '') => {
    if (!obj || typeof obj !== 'object') return;
    
    Object.entries(obj).forEach(([key, value]) => {
      const currentPath = path ? `${path}.${key}` : key;
      if (Array.isArray(value) && value.length > 0) {
        console.log(`找到数组: ${currentPath}, 长度: ${value.length}`, value);
        debugInfo.value += `\n找到数组: ${currentPath}, 长度: ${value.length}`;
        
        // 尝试使用第一个找到的非空数组，并过滤已删除数据
        if (tableData.value.length === 0) {
          const filteredValue = value.filter((item: any) => item.Status !== '已删除');
          tableData.value = filteredValue;
          total.value = filteredValue.length;
          debugInfo.value += `\n使用路径 ${currentPath} 的数据，过滤后剩余${filteredValue.length}条记录`;
          ElMessage.success(`找到备选数据源: ${currentPath}，过滤后剩余${filteredValue.length}条记录`);
        }
      }
      
      // 递归搜索更深层次
      findArrays(value, currentPath);
    });
  };
  
  try {
    const response = await axios.get('http://localhost:5109/api/PregnancyExamination/list')
    debugInfo.value += '\n直接请求成功: ' + JSON.stringify(response.data)
    
    // 根据实际数据结构解析
    if (response.data && response.data.data && response.data.data.PageData) {
      // 过滤已删除数据
      const filteredData = response.data.data.PageData.filter((item: any) => item.Status !== '已删除');
      tableData.value = filteredData;
      total.value = filteredData.length;
      ElMessage.success(`直接获取成功，找到${filteredData.length}条数据(已过滤已删除)`)
      debugInfo.value += `\n成功获取到${filteredData.length}条数据(已过滤已删除数据)`
    } else if (response.data && response.data.PageData) {
      // 过滤已删除数据
      const filteredData = response.data.PageData.filter((item: any) => item.Status !== '已删除');
      tableData.value = filteredData;
      total.value = filteredData.length;
      ElMessage.success(`直接获取成功，找到${filteredData.length}条数据(备选路径，已过滤已删除)`)
      debugInfo.value += `\n成功获取到${filteredData.length}条数据(备选路径，已过滤已删除数据)`
    } else {
      debugInfo.value += '\n未找到有效数据，尝试深度搜索...'
      
      findArrays(response.data);
      
      if (tableData.value.length === 0) {
        debugInfo.value += '\n未找到任何数组数据';
      }
    }
  } catch (error) {
    console.error('直接获取失败:', error)
    debugInfo.value += '\n直接获取失败: ' + JSON.stringify(error)
    
    // 尝试备选URL
    try {
      debugInfo.value += '\n尝试备选URL...'
      const altResponse = await axios.get('http://39.96.200.62:8411/PregnancyExamination/list')
      debugInfo.value += '\n备选请求成功: ' + JSON.stringify(altResponse.data)
      
      // 再次尝试解析数据
      if (altResponse.data && altResponse.data.data && altResponse.data.data.PageData) {
        const filteredData = altResponse.data.data.PageData.filter((item: any) => item.Status !== '已删除');
        tableData.value = filteredData;
        total.value = filteredData.length;
        ElMessage.success(`备选URL获取成功，过滤后剩余${filteredData.length}条记录`)
      } else if (altResponse.data && altResponse.data.PageData) {
        const filteredData = altResponse.data.PageData.filter((item: any) => item.Status !== '已删除');
        tableData.value = filteredData;
        total.value = filteredData.length;
        ElMessage.success(`备选URL获取成功(备选路径)，过滤后剩余${filteredData.length}条记录`)
      } else {
        // 深度搜索任何数组
        findArrays(altResponse.data);
      }
    } catch (altError) {
      debugInfo.value += '\n备选URL也失败: ' + JSON.stringify(altError)
    }
  } finally {
    loading.value = false
  }
}

// 使用模拟数据测试
const testMockData = async () => {
  // 确保先加载耳号映射表
  if (Object.keys(earNumberMap.value).length === 0) {
    await fetchEarNumberList()
  }
  if (Object.keys(buildingMap.value).length === 0) {
    await fetchBuildingList()
  }
  if (Object.keys(penMap.value).length === 0) {
    await fetchPenList()
  }
  
  const mockData = [
    {
      ExaminationId: 1,
      EarTag: "测试01",
      PregnancyCheckDate: "2023-07-24",
      PregnancyResult: "阳性",
      PregnancyMethod: "B超",
      FetusCount: 2,
      GestationDays: 30,
      CurrentPen: "A区",
      CurrentStall: "01",
      TransferPen: "B区",
      TransferStall: "02",
      ResponsiblePerson: "张三",
      Creator: "admin",
      CreateTime: "2023-07-24 09:00:00",
      Modifier: "",
      ModifyTime: null,
      Approver: "",
      ApprovalTime: null,
      DocumentNumber: "PRE2023072401",
      RecordType: "常规",
      Status: "正常"
    },
    {
      ExaminationId: 2,
      EarTag: "测试02",
      PregnancyCheckDate: "2023-07-25",
      PregnancyResult: "阴性",
      PregnancyMethod: "直检",
      FetusCount: 0,
      GestationDays: 0,
      CurrentPen: "A区",
      CurrentStall: "03",
      TransferPen: "",
      TransferStall: "",
      ResponsiblePerson: "李四",
      Creator: "admin",
      CreateTime: "2023-07-25 10:00:00",
      Modifier: "",
      ModifyTime: null,
      Approver: "",
      ApprovalTime: null,
      DocumentNumber: "PRE2023072502",
      RecordType: "常规",
      Status: "正常"
    },
    {
      ExaminationId: 3,
      EarTag: "测试03",
      PregnancyCheckDate: "2023-07-26",
      PregnancyResult: "阳性",
      PregnancyMethod: "B超",
      FetusCount: 1,
      GestationDays: 45,
      CurrentPen: "B区",
      CurrentStall: "05",
      TransferPen: "",
      TransferStall: "",
      ResponsiblePerson: "王五",
      Creator: "admin",
      CreateTime: "2023-07-26 11:00:00",
      Modifier: "admin",
      ModifyTime: "2023-07-26 11:30:00",
      Approver: "",
      ApprovalTime: null,
      DocumentNumber: "PRE2023072603",
      RecordType: "常规",
      Status: "已删除" // 这条记录不应该显示
    }
  ]
  
  // 过滤已删除的记录
  const filteredMockData = mockData.filter(item => item.Status !== '已删除')
  
  tableData.value = filteredMockData
  total.value = filteredMockData.length
  debugInfo.value = `已加载模拟数据: ${mockData.length} 条记录，过滤后剩余 ${filteredMockData.length} 条记录`
  ElMessage.success(`已加载模拟数据，过滤后剩余 ${filteredMockData.length} 条记录`)
}

// 关闭调试面板
const closeDebug = () => {
  showDebug.value = false
  debugInfo.value = ''
}

// 处理表格选择变化
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}

// 处理每页数量变化
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  fetchTableData()
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  queryParams.pageIndex = val
  fetchTableData()
}

// 处理跳转页码
const handleGoToPage = () => {
  const page = parseInt(goToPage.value)
  if (page && page > 0 && page <= Math.ceil(total.value / queryParams.pageSize)) {
    queryParams.pageIndex = page
    fetchTableData()
  } else {
    ElMessage.warning('请输入有效的页码')
  }
  goToPage.value = ''
}

// 处理添加
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 跳转到新增页面
const goToAddPage = () => {
  router.push('/EwePregnancyExaminationAdd')
}

// 处理编辑
const handleEdit = (row: any) => {
  router.push({
    path: '/EwePregnancyExaminationEdit',
    query: {
      id: row.ExaminationId
    }
  })
}

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除该条种母妊检记录吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 获取当前登录用户名，如果没有则使用默认值
      const currentUser = localStorage.getItem('username') || '系统管理员'
      const res = await deletePregnancyExamination(row.ExaminationId, currentUser, `用户${currentUser}删除记录`)
      
      if (res.data && res.data.code === 200) {
        ElMessage.success('删除成功')
        fetchTableData()
      } else {
        ElMessage.error(res.data?.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除种母妊检记录失败:', error)
      ElMessage.error('删除失败，请检查网络连接')
    }
  }).catch(() => {})
}

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }
  
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条记录吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const ids = selectedRows.value.map(item => item.ExaminationId)
      // 获取当前登录用户名，如果没有则使用默认值
      const currentUser = localStorage.getItem('username') || '系统管理员'
      // 使用批量删除API
      const res = await batchDeletePregnancyExamination(
        ids, 
        currentUser, 
        `用户${currentUser}批量删除${ids.length}条记录`
      )
      
      if (res.data && res.data.code === 200) {
        ElMessage.success(`成功删除 ${ids.length} 条记录`)
        fetchTableData()
      } else {
        ElMessage.error(res.data?.msg || '批量删除失败')
      }
    } catch (error) {
      console.error('批量删除种母妊检记录失败:', error)
      ElMessage.error('批量删除失败，请检查网络连接')
    }
  }).catch(() => {})
}

// 处理显示/隐藏已删除数据切换
const handleShowDeletedChange = (val: boolean) => {
  queryParams.excludeDeleted = !val
  fetchTableData()
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    ExaminationId: '',
    EarTag: '',
    PregnancyCheckDate: '',
    PregnancyResult: '',
    PregnancyMethod: '',
    FetusCount: 0,
    GestationDays: 0,
    CurrentPen: '',
    CurrentStall: '',
    TransferPen: '',
    TransferStall: '',
    ResponsiblePerson: '',
    Creator: '',
    CreateTime: '',
    Modifier: '',
    ModifyTime: '',
    Approver: '',
    ApprovalTime: '',
    DocumentNumber: '',
    RecordType: '',
    Status: ''
  })
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) {
      return false
    }
    
    try {
      if (dialogType.value === 'add') {
        const res = await addPregnancyExamination(form)
        if (res.data && res.data.code === 200) {
          ElMessage.success('添加成功')
          dialogVisible.value = false
          fetchTableData()
        } else {
          ElMessage.error(res.data?.msg || '添加失败')
        }
      } else {
        const res = await updatePregnancyExamination(form)
        if (res.data && res.data.code === 200) {
          ElMessage.success('更新成功')
          dialogVisible.value = false
          fetchTableData()
        } else {
          ElMessage.error(res.data?.msg || '更新失败')
        }
      }
    } catch (error) {
      console.error('提交种母妊检数据失败:', error)
      ElMessage.error('操作失败，请检查网络连接')
    }
  })
}

// 格式化日期
const formatDate = (row: any, column: any, cellValue: any) => {
  if (!cellValue) return '';
  
  // 处理日期格式
  try {
    const date = new Date(cellValue);
    if (isNaN(date.getTime())) return cellValue; // 如果转换失败，返回原始值
    
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    
    return `${year}-${month}-${day}`;
  } catch (error) {
    return cellValue; // 发生错误时返回原始值
  }
};

// 格式化种母耳号，将ID转换为名称
const formatEarTag = (earTagId: any) => {
  if (!earTagId) return '';
  
  // 处理可能是数字的情况
  const tagId = String(earTagId);
  
  // 检查映射表中是否有对应的名称
  if (earNumberMap.value && earNumberMap.value[tagId]) {
    return earNumberMap.value[tagId];
  }
  
  // 如果没有找到映射，返回原始ID
  return tagId;
}

// 格式化栏位，将ID转换为名称
const formatBuilding = (buildingId: any) => {
  if (!buildingId) return '';
  
  // 处理可能是数字的情况
  const id = String(buildingId);
  
  // 检查映射表中是否有对应的名称
  if (buildingMap.value && buildingMap.value[id]) {
    return buildingMap.value[id];
  }
  
  // 如果没有找到映射，返回原始ID
  return id;
}

// 格式化栏号，将ID转换为名称
const formatPen = (penId: any) => {
  if (!penId) return '';
  
  // 处理可能是数字的情况
  const id = String(penId);
  
  // 检查映射表中是否有对应的名称
  if (penMap.value && penMap.value[id]) {
    return penMap.value[id];
  }
  
  // 如果没有找到映射，返回原始ID
  return id;
}
</script>

<style scoped>
.pregnancy-examination-container {
  padding: 20px;
}

.search-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.operation-btns {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.debug-panel {
  background-color: #fef0f0;
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 4px;
  border: 1px solid #fde2e2;
}

.debug-actions {
  margin-bottom: 10px;
}

.debug-info {
  max-height: 300px;
  overflow-y: auto;
  background-color: #f8f8f8;
  padding: 10px;
  border-radius: 4px;
  font-family: monospace;
  font-size: 12px;
  white-space: pre-wrap;
  word-break: break-all;
}
</style>
